package com.chu.utils;

import com.chu.entity.Employee;
import com.chu.entity.Menu;
import com.chu.entity.Role;
import com.chu.mapper.EmployeeMapper;
import com.chu.mapper.MenuMapper;
import com.chu.mapper.RoleMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private MenuMapper menuMapper;


    @Override//授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权开始");
        //得到认证通过后的用户信息
        Employee employee = (Employee) principalCollection.getPrimaryPrincipal();
        Role role = roleMapper.selectByPrimaryKey(employee.getRoleid());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole(role.getRname());
        List<Menu> permission = menuMapper.findPermissionByRoleId(role.getRoleid());
        ArrayList permissionList = new ArrayList();
        for (Menu menu : permission) {
            permissionList.add(menu.getPercode());
        }
        info.addStringPermissions(permissionList);
        return info;
    }

    @Override//认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证开始");

        //得到用户提交的信息
        String  username = (String) authenticationToken.getPrincipal();
        Employee employee = employeeMapper.loginByLoginName(username);
        if(employee==null){

            System.out.println("认证结束1");
            return null;
        }else{

            System.out.println("认证结束2");
            return new SimpleAuthenticationInfo(employee,employee.getLoginpassword(), ByteSource.Util.bytes(employee.getSalt()),"myRealm");
        }
    }
}
